export default function Paul_Pio(prop) {
  let current = {
    canvas: document.getElementById("pio"),
    body: document.querySelector(".pio-container"),
  };

  /* - 方法 */
  let modules = {
    // 创建内容
    create(tag, prop) {
      let e = document.createElement(tag);
      if (prop.class) e.className = prop.class;
      return e;
    },
    // 随机内容
    rand(arr) {
      return arr[Math.floor(Math.random() * arr.length + 1) - 1];
    },
    // 创建对话框方法
    render(text) {
      if (text.constructor === Array) {
        dialog.innerHTML = modules.rand(text);
      } else if (text.constructor === String) {
        dialog.innerHTML = text;
      } else {
        dialog.innerHTML = "输入内容出现问题了 X_X";
      }

      dialog.classList.add("active");

      clearTimeout(this.t);
      this.t = setTimeout(function () {
        dialog.classList.remove("active");
      }, 6000);
    },
  };
  this.modules = modules;

  let elements = {
    show: modules.create("div", {class: "pio-show"})
  };

  let dialog = modules.create("div", {class: "pio-dialog"});
  current.body.appendChild(dialog);
  current.body.appendChild(elements.show);

  // 运行
  this.init = onlyText => {
    if (!onlyText) {
      this.model = loadlive2d("pio", prop.model, model => {
        const canvas = document.getElementById("pio")
        const coreModel = model.internalModel.coreModel
        const motionManager = model.internalModel.motionManager

        this.playAction = (action) => {
          action.text && this.modules.render(action.text)
          action.motion && this.model.motion(action.motion)

          if (action.from && action.to) {
            Object.keys(action.from).forEach(id => {
              const hidePartIndex = coreModel._partIds.indexOf(id)
              TweenLite.to(coreModel._partOpacities, 0.6, {[hidePartIndex]: action.from[id]});
              // coreModel._partOpacities[hidePartIndex] = action.from[id]
            })

            motionManager.once("motionFinish", (data) => {
              Object.keys(action.to).forEach(id => {
                const hidePartIndex = coreModel._partIds.indexOf(id)
                TweenLite.to(coreModel._partOpacities, 0.6, {[hidePartIndex]: action.to[id]});
                // coreModel._partOpacities[hidePartIndex] = action.to[id]
              })
            })
          }
        }

        canvas.onclick = () => {
          if (motionManager.state.currentGroup !== "Idle") return

          const action = this.modules.rand(prop.touchList)
          this.playAction(action)
        }

        prop?.welcome && this.playAction(prop.welcome())
        prop?.onload?.(this);
      });
    }

    current.canvas.onclick = () => {
      modules.render(prop.touchList || ["你在干什么？", "再摸我就报警了！", "HENTAI!", "不可以这样欺负我啦！"]);
    };
  };

  this.init();
};